#coding=utf-8

import pymongo
client = pymongo.MongoClient("localhost",27017)
from bson import ObjectId

'''dao实验'''

#板
def get_all_boards():
    dbs = client.database_names()
    dbs.remove("local")
    #测试时未建以下两个表
    #dbs.remove("admin")
    #dbs.remove("test")
    return dbs

def add_board(name):
    db = pymongo.database.Database(client,name)
    db.init.save({"init":"init"})
    return db

def del_board(name):
    client.drop_database(name)
    return True

def rename_board(old_name,new_name):
    copyreturn = client.copy_database(from_name=old_name,to_name=new_name)
    if copyreturn.get(u"ok") == 1.0:
        client.drop_database(old_name)
    else:
        return False
    return True

#列
def get_lists_from_boards_name(bname):
    db = pymongo.database.Database(client,bname)
    lists = db.collection_names(include_system_collections=False)
    lists.remove("init")
    return lists

def add_list(bname,lname):
    db = pymongo.database.Database(client,bname)
    _list = db.create_collection(lname)
    init_id = _list.save({"init":"init"})
    if init_id != None:
        return True
    else:
        return False

def del_list(bname,lname):
    db = pymongo.database.Database(client,bname)
    db[lname].drop()
    return True

def rename_list(bname,old_name,new_name):
    db = pymongo.database.Database(client,bname)
    db[old_name].rename(new_name)
    return True

#卡
def get_cards_from_lists_name(bname,lname):
    db = pymongo.database.Database(client,bname)
    coll = db[lname]
    cards = list(coll.find({"init":{"$nin":["init"]}}))
    return cards

def add_card(bname,lname,content):
    db = pymongo.database.Database(client,bname)
    card_id = db[lname].save({"card_content":content})
    return str(card_id)

def del_card(bname,lname,card_id):
    db = pymongo.database.Database(client,bname)    
    db[lname].remove({"_id":ObjectId(card_id)})
    return True
    
def recontent_card(bname,lname,card_id,new_content):
    db = pymongo.database.Database(client,bname)
    db[lname].update({"_id":ObjectId(card_id)},{"$set":{"card_content":new_content}})
    return True
